<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">

    <meta http-equiv=" X-UA-Compatible" content="ie=edge">
    <meta name="viewport"
        content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">

    <title>易画板</title>
    <style type="text/css">
        .icon {
            width: 1em;
            height: 1em;
            vertical-align: -0.15em;
            fill: currentColor;
            overflow: hidden;
        }
    </style>
    <link rel="stylesheet" href="./style.css">
</head>

<body>
    <canvas id="canvas"></canvas>
    <div class="color-group">
        <ul>
            <li id="black" class="color-item active" style="background-color: black;"></li>
            <li id="red" class="color-item" style="background-color: rgb(255, 0, 0);"></li>
            <li id="orange" class="color-item" style="background-color: rgb(255, 128, 0);"></li>
            <li id="yellow" class="color-item" style="background-color: rgb(225, 255, 0);"></li>
            <li id="green" class="color-item" style="background-color: rgb(0, 255, 0);"></li>
            <li id="blue" class="color-item" style="background-color: rgb(23, 147, 245);"></li>
            <li id="indigo" class="color-item" style="background-color: rgb(47, 7, 168);"></li>
            <li id="purple" class="color-item" style="background-color: rgb(115, 37, 182);"></li>
            <li id="gray" class="color-item" style="background-color: gray;"></li>
        </ul>
    </div>
    <div id="range-wrap"><input type="range" id="range" min="1" max="50" value="5" title="调整笔刷粗细"></div>
    <div class="tools">
        <button id="pen" title="画笔" class="active">
            <svg class="icon">
                <use xlink:href="#icon-pen"></use>
            </svg>
        </button>
        <button id="eraser" title="橡皮擦">
            <svg class="icon">
                <use xlink:href="#icon-eraser"></use>
            </svg>
        </button>
        <button id="clear" title="清空">
            <svg class="icon">
                <use xlink:href="#icon-clear"></use>
            </svg>
        </button>
        <button id="save" title="保存">
            <svg class="icon">
                <use xlink:href="#icon-save"></use>
            </svg>
        </button>

    </div>
    <script src="//at.alicdn.com/t/font_3145146_evvnbfondk6.js"></script>
    <script>
        // 初始化
        let canvas = document.getElementById("canvas");
        let context = canvas.getContext("2d");
        let pen = document.getElementById("pen");
        let eraser = document.getElementById("eraser");
        let reset = document.getElementById("clear");
        let currentColor = document.getElementsByClassName("color-item");

        // 橡皮状态，默认false
        let clear = false;
        let activeColor = 'black';

        // 初始化背景颜色


        const setCanvasBg = (color) => {
            context.fillStyle = color;
            context.fillRect(0, 0, canvas.width, canvas.height);
            context.fillStyle = "black";
        }
        setCanvasBg('white');

        getColor();
        // 刷新页面警告TODO
        window.onbeforeunload = () => {
            return "Reload site?";
        };

        // 画布大小设置
      

        function autoSetSize(canvas) {
            canvasSetSize();

            function canvasSetSize() {
                let pageWidth = document.documentElement.clientWidth;
                let pageHeight = document.documentElement.clientHeight;

                canvas.width = pageWidth;
                canvas.height = pageHeight;
            }

            window.onresize = function () {
                canvasSetSize();
            }
        }

        autoSetSize(canvas);

        // -------------------------------------------------------------------
        // 响应设备绘画
        const draw = (canvas) => {
            let painting = false;
            let last
            var isTouchDevice = 'ontouchstart' in
                document.documentElement
            if (isTouchDevice) {
                canvas.ontouchstart = (e) => {
                    this.firstDot = context.getImageData(0, 0, canvas.width, canvas
                        .height); //在这里储存绘图表面
                    painting = true;

                    let x = e.touches[0].clientX;
                    let y = e.touches[0].clientY;
                    last = [x, y]
                    context.save();
                    drawCircle(x, y, lWidth / 2);
                };
                canvas.ontouchmove = (e) => {
                    if (painting) {
                        let x = e.touches[0].clientX;
                        let y = e.touches[0].clientY;
                        drawLine(last[0], last[1], x, y);
                        last = [x, y];
                    }
                };

                canvas.ontouchend = () => {
                    painting = false;
                }
            } else {
                canvas.onmousedown = (e) => {
                    this.firstDot = context.getImageData(0, 0, canvas.width, canvas
                        .height); //在这里储存绘图表面
                    painting = true;
                    let x = e.clientX;
                    let y = e.clientY;
                    last = [x, y]
                    context.save();
                    drawCircle(x, y, lWidth / 2);
                };
                canvas.onmousemove = (e) => {
                    if (painting) {
                        drawLine(last[0], last[1], e.clientX, e.clientY);
                        last = [e.clientX, e.clientY];
                    }
                };

                canvas.onmouseup = function () {
                    painting = false;
                };

                canvas.mouseleave = function () {
                    painting = false;
                }
            }
        }
        draw(canvas);

        // -------------------------------------------------------------
        // 画笔功能
        let lWidth = 6;
        // 单击画点
        const drawCircle = (x, y, size) => {
            if (!clear) {
                context.beginPath();
                context.arc(x, y, size, 0, Math.PI * 2);
                context.fill();
                context.closePath();
            }
            if (clear) {
                context.beginPath();
                context.arc(x, y, 0, 0, Math.PI * 2);
                context.fill();
                context.clip();
                context.globalCompositeOperation = "destination-out";
                context.clearRect(0, 0, canvas.width, canvas.height);
                context.restore();
                context.closePath();
            }
            context.save();

        }
        // 移动画线
        drawLine = function (x1, y1, x2, y2) {
            context.lineWidth = lWidth;
            context.lineCap = "round";
            context.lineJoin = "round";

            if (clear) {
                context.beginPath();
                context.globalCompositeOperation = "destination-out";
                context.moveTo(x1, y1);
                context.lineTo(x2, y2);
                context.stroke();
                context.clip();
                context.clearRect(0, 0, canvas.width, canvas.height);
                context.restore();
                context.closePath();
            } else {
                context.beginPath();
                context.moveTo(x1, y1);
                context.lineTo(x2, y2);
                context.stroke();
                context.closePath();
            }
            context.save();
        }
        // 铅笔
        pen.onclick = function () {
            clear = false;
            this.classList.add("active");
            eraser.classList.remove("active");
        };
        // 橡皮
        eraser.onclick = function () {
            clear = true;
            this.classList.add("active");
            pen.classList.remove("active");
        };
        // 清空画板
        reset.onclick = function () {
            context.clearRect(0, 0, canvas.width, canvas.height);
            setCanvasBg('white');
        };
        // 放入a标签中，保存
        save.onclick = function () {
            let imgUrl = canvas.toDataURL("image/png");
            let save = document.createElement("a");
            document.body.appendChild(save);
            save.href = imgUrl;
            save.download = "绘画" + (new Date).getTime();
            save.target = "_blank";
            save.click();
        };
        // 获取颜色
        function getColor() {
            for (let i = 0; i < currentColor.length; i++) {
                currentColor[i].onclick = function () {
                    for (let i = 0; i < currentColor.length; i++) {
                        currentColor[i].classList.remove("active");
                        this.classList.add("active");
                        activeColor = this.style.backgroundColor;
                        context.fillStyle = activeColor;
                        context.strokeStyle = activeColor;
                    }
                }
            }
        }

        // 画笔粗细
        range.onchange = function () {
            lWidth = this.value;
        };
    </script>
</body>

</html>
